package com.atguigu.juc.juc_3utils;

import java.util.Random;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

/**
 * @Author yanglin [2533188365@qq.com]
 * @Create 2024-04-26 16:25
 * @Description:
 */
public class CountDownLatchDemo {


    /**
     * CountDownLatch可以用于控制一个或多个线程等待多个任务完成后在执行
     * CountDownLatch的计数器只能够被减少，不能够被增加
     * CountDownLatch的计数器初始值为正整数，每次调用countDown()方法会将计数器减1，计数器为0时，等待线程开始执行
     */

    public static void main(String[] args) {

        //初始化计数器为6
        CountDownLatch countDownLatch = new CountDownLatch(6);

        for (int i = 0; i < 6; i++) {
            int temp = i;
            new Thread(() -> {
                try {
                    TimeUnit.SECONDS.sleep(temp + 1);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                System.out.println(Thread.currentThread().getName() + "\t 离开了");
                //计数器减1
                countDownLatch.countDown();
            },String.valueOf(i)).start();
        }

        try {
            //没有减到0之前，主线程一直处于阻塞状态
            countDownLatch.await();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }


        System.out.println("所有任务已经执行完成");

    }

}
